<script setup>
import axios from 'axios';
import {ElMessageBox,ElNotification } from 'element-plus'
import { onMounted, ref } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import {queryAllApi,delDeptApi,addDeptApi,queryDeptByIdApi,updateDeptApi} from '@/api/dept'
const deptList = ref([])
const formTitle = ref('')
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
// 增加部门
const form = ref({
  name: ''
})
// 表单引用
const ruleDeptRef = ref('')
// 表单验证规则
const deptRules = ref({
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ]
})
// 查询所有部门
const queryAll=async ()=>{
  const res = await queryAllApi('/depts');
  deptList.value = res.data; 
}
// 新增部门
const toAdd = async()=>{
  formTitle.value = '新增部门'
  dialogFormVisible.value = true
  form.value = {name:''}
  // 重置表单验证
  ruleDeptRef.value.resetFields()
}
const submit = async () => {
  // 正确的表单验证方式
  try {
    await ruleDeptRef.value.validate()
    
    // 验证通过后执行添加操作
    let res = null;
    let msg = '';
    if(form.value.id){  // 非空非0即为true
      res = await updateDeptApi(form.value); // 修改
      msg = '数据已修改'
    }else{ 
      res = await addDeptApi(form.value); // 新增
       msg = '数据已添加'
    }
  
     if (res.code == 1) {
        ElNotification({
        title: '操作成功',
        message: msg,
        type: 'success',
      })
      dialogFormVisible.value = false
      queryAll()
    }
   
  } catch (error) {
    // 验证失败时的处理
    console.log('表单验证失败:', error)
    return false
  }
}
// 修改部门
const toEdit = async (id) => {
  formTitle.value = '修改部门'
  dialogFormVisible.value = true
  const res = await queryDeptByIdApi(id)
  console.log(res);
  form.value = res.data
}
// 删除部门
const delDept =(id)=>{
  console.log(`Delete item with ID ${id}`);
   ElMessageBox.confirm(
    '是否删除该部门？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
       const res = await delDeptApi(id);
      if(res.code == 1){
       ElNotification({
        title: '删除成功',
        message: '数据已被删除',
        type: 'success',
      })
        queryAll()
      }
      else{
        ElNotification({
        title: '删除失败',
        message: res.msg,
        type: 'error',
      }) 
      }
    })
    .catch(() => {
      ElNotification({
        type: 'info',
        message: '取消删除',
      })
    })
 
}
onMounted(() => {
  queryAll()
})
</script>

<template>
  <div class="dept-container">
    <div class="header-section">
      <h2 class="page-title">部门管理</h2>
      <el-button type="primary" plain class="add-btn" @click="toAdd()">
        <el-icon><Plus /></el-icon>
        新增部门
      </el-button>
    </div>
    <!-- 添加部门对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="formTitle" width="500">
    <el-form :model="form" ref="ruleDeptRef" :rules="deptRules" >
      <el-form-item label="部门名称" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submit()">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
    <!-- 表格 -->
    <el-card class="table-card">
      <el-table :data="deptList" border stripe class="dept-table">
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="部门名称" min-width="200"></el-table-column>
        <el-table-column prop="updateTime" label="最后操作时间" min-width="200"></el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" class="table-btn" @click="toEdit(scope.row.id)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" class="table-btn" @click="delDept(scope.row.id)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<style scoped>
.dept-container {
  padding: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.page-title {
  color: #303133;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.add-btn {
  padding: 10px 20px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: none;
}

.dept-table {
  width: 100%;
}

.dept-table :deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.dept-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.table-btn {
  margin: 0 5px;
}

.table-btn:first-child {
  margin-left: 0;
}

.table-btn:last-child {
  margin-right: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .add-btn {
    margin-top: 15px;
  }
  
  .dept-table {
    font-size: 12px;
  }
  
  .table-btn span {
    display: none;
  }
  
  .table-btn .el-icon {
    margin-right: 0;
  }
}
</style>